package gen.tools.query;

import gen.tools.Widgets;
import gen.tools.structures.S3;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.google.gson.Gson;

public class QueryErrorLogs extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryErrorLogs() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");

		int limitedQueryRowNumber = wid.getParNumberFromRequest( request.getParameter("queryRowLimitedNumber"));
		
		if ( limitedQueryRowNumber ==0 ) {
			limitedQueryRowNumber = 1;
		}
		List<S3> errmes = null;	//欲回傳的查詢結構
		
		try {
			//從AP Server的JNDI取得data source
			Context ctx = new InitialContext();
			DataSource dataSource = (DataSource) ctx.lookup( wid.JNDINAME );
			
			
			JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
			jdbcTemplate.setMaxRows(limitedQueryRowNumber);
			String sql = "SELECT createdDateTime,errMes,des FROM errmes ORDER BY errMesId DESC";			
			
			errmes = jdbcTemplate.query(sql,
				new RowMapper<S3>() {
                	public S3 mapRow(ResultSet rs, int rowNum) throws SQLException {
                		return new S3(wid.changeTimeFormat(rs.getTimestamp("createdDateTime")), rs.getString("errMes"),
                            rs.getString("des"));
                	}
            });
		} catch (Exception e) {
			wid.errLog(e);
		}
		
		response.getWriter().write( new Gson().toJson(errmes) );
	}
}
